const service = require('../settingService.js')
var timeCount = 60;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    btnTitle:"获取验证码",
    phone:"",
    code:"",
    timeCounting:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },
  
  inputPhone: function (e) {
    let self = this;
    if (e.detail.value.length > 11) {
      self.setData({
        phone: self.data.phone
      })
      return
    }
    self.setData({
      phone: e.detail.value
    });
  },

  inputCode: function (e) {
    let self = this;
    if (e.detail.value.length > 6) {
      self.setData({
        code: self.data.code
      })
      return
    }
    self.setData({
      code: e.detail.value
    });
  },

  /**
   *  获取验证码
   */
  sendCode:function(){
    if (this.data.timeCounting == true) {
      return;
    }
    if (this.data.phone && this.data.phone.length == 11) {
      var self = this;
      let param = { "mobile": this.data.phone };
      service.sendCode(param, function (res) {
        if (res.code == 200){
          self.updateTime();
          self.showTost("获取验证码成功")
        }else{
          self.showTost(res.message)
        }
      })
    }else{
      this.showTost('请输入正确的手机号')
    }
  },

  /**
   * 绑定手机号
   */
  submit:function(){
    var self = this;
    if (!this.data.phone || this.data.phone.length != 11){
      self.showTost('请输入正确的手机号')
      return      
    }
    if (!this.data.code) {
      self.showTost('请输入验证码')
      return
    }
    let param = { "mobile": this.data.phone, "code" : this.data.code};
    service.bindPhone(param, function (res) {
      if(res.code == 200){
        self.showTost('绑定成功')
        // 返回上一页面 
        wx.navigateBack({
          delta: 1  //返回的页面数，如果 delta 大于现有页面数，则返回到首页。
        })
      }else{
        self.showTost(res.message)
      }
    })
  },

  showTost: function (msg){
    wx.showToast({
      title: msg,
      icon: 'none',
    })
  },

  updateTime: function () {
    console.log("准备倒计时")
    if (this.data.timeCounting == true) {
      return;
    }
    this.setData({
      timeCounting: true
    });
    console.log("开始倒计时")
    var interval = setInterval(function () {
      this.setData({
        btnTitle: timeCount,
        timeCounting: true
      });
      timeCount--;
      if (timeCount < 0) {
        clearInterval(interval);
        timeCount = 60;
        this.setData({
          btnTitle:"重新发送",
          timeCounting: false
        });
      }
    }.bind(this), 1000);
  },
})